package sivan.test;

import lombok.Data;

/**
 * 多线程实现ABABAB
 */
public class ThreadABABDemo {

    @Data
    public static class MyThread extends Thread {

        private static final Object object = new Object();
//        private final Object object;
        private String str;
        private boolean flag;
        private MyThread next;

        public MyThread(Object object, String name, boolean flag) {
            this.str = name;
            this.flag = flag;
//            this.object = object;
        }

        public void changeFlag() {
            this.flag = !this.flag;
        }

        @Override
        public void run() {
            synchronized (object) {
                for (int i = 0; i < 50; i++) {
                    while (flag) {
                        try {
                            object.wait();
                        } catch (InterruptedException e) {
                            System.out.println("线程发生中断" + str);
                        }
                    }
                    if(str.equals("A")) {
                        System.out.println(str);
                    } else {
                        System.out.print(str);
                    }
                    this.changeFlag();
                    this.next.changeFlag();
                    object.notifyAll();
                }
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Object object = new Object();
        MyThread a = new MyThread(object, "A", true);
        MyThread b = new MyThread(object, "B", true);
        MyThread c = new MyThread(object, "C", true);
        MyThread d = new MyThread(object, "D", true);
        MyThread e = new MyThread(object, "E", true);
        MyThread f = new MyThread(object, "F", false);

        a.setNext(f);
        b.setNext(a);
        c.setNext(b);
        d.setNext(c);
        e.setNext(d);
        f.setNext(e);

        a.start();
        b.start();
        c.start();
        d.start();
        e.start();
        f.start();

//        a.join();
//        b.join();
        a.join();
        System.out.println("主线程结束");
    }
}
